<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta charset="utf-8" />
    <!--script src="https://unpkg.com/pdf-lib"></script-->
    <script src="jquery-2.2.1.min.js"></script>
    <script src="pdf-lib.min.js"></script>
    <style type="text/css">
			.center-text {
				text-align: center;
			}
			
			.inputfile {
				opacity: 0;
			}

			.lab {
				border-radius: 10px;
				background-color: #cc99ff;
				font-family: 楷体;
				font-size: 24px;
			}
			.boxwidth{
				width: 60px;
			}
		</style>
  </head>

  <body>
    <h3 class="center-text">图片转Pdf</h3><br />
	<div class="center-text">
		<label for="resolution">分辨率</label>	
		<input type="text" id="resolution" class="center-text boxwidth" value="200" />
	</div>
	<div class="center-text">
		<input type="file" name="file1" id="file1" class="inputfile" accept="image/*" multiple="multiple" /><br />
		<label for="file1" class='lab'>打开图片</label><br /><br />
		<div class="center-text" id="img_info"></div>
	</div>
  </body>

  <script>
    function add0(m){
      return m<10?('0'+m):m
     }
		function getSaveFileName(baseFileName){
				var time = new Date();
				var y = time.getFullYear();
				var m = time.getMonth()+1;
				var d = time.getDate();
				var h = time.getHours();
				var mm = time.getMinutes();
				var s = time.getSeconds();
				return baseFileName+'_'+y+add0(m)+add0(d)+'_'+add0(h)+add0(mm)+add0(s)+".pdf";
			
     }
			function downLoad(url,baseFileName){
				var oA = document.createElement("a");
				oA.download = getSaveFileName(baseFileName);// 设置下载的文件名，默认是'下载'
				oA.href = url;
				document.body.appendChild(oA);
				oA.click();
				oA.remove(); // 下载之后把创建的元素删除
			}

    const getImage = async (imageUrl) => {  
			  return new Promise((resolve, reject) => {  
				const image = new Image();  
				image.crossOrigin = 'Anonymous'; // 这允许图像从不同的源加载  
				image.src = imageUrl;  
				image.onload = () => {  
				  resolve(image);  
				};  
				image.onerror = reject;  
			  }); 
			};
			// 获取图片并将其转换为canvas  
			const getImageCanvas = async (image) => { 
			  return new Promise((resolve, reject) => { 
				const canvas = document.createElement('canvas'); 
				canvas.width = image.width; 
				canvas.height = image.height; 
				canvas.style.backgroundColor = '#FFFFFF';
				var ctx=canvas.getContext('2d');
				ctx.drawImage(image, 0, 0); 
				resolve(canvas);
			  }); 
			}; 

			//file extends blob
			function createURL(file) {
				var url = null;
				if (window.createObjectURL != undefined) {
					url = window.createObjectURL(file);
				} else if (window.URL != undefined) { // mozilla(firefox)  
					url = window.URL.createObjectURL(file);
				} else if (window.webkitURL != undefined) { // webkit or chrome  
					url = window.webkitURL.createObjectURL(file);
				}
				return url;
			};
			function getExt(name){		
				var index=name.lastIndexOf(".");
				return index>=0?name.substring(index,name.length):"";
			}
			function ImageType(isCommon,type){
				this.isCommon=isCommon;
				this.type=type;
			}
			function getImageType(name){
				const ext=getExt(name).toLowerCase();
				if(ext===".jpg"||ext===".jpeg")return new ImageType(true,'JPEG');
				if(ext===".png")return new ImageType(true,'PNG');
				return new ImageType(false,'JPEG');
			}

      const img2pdf=async (files,resolution=200) => {
				//console.log("img2pdf",files);
        const k=resolution/72.0;
				  // 创建一个新的PDF文件  
        const pdfDoc = await PDFLib.PDFDocument.create();
        pdfDoc.setCreator('pdf-lib');
        pdfDoc.setProducer('pdf-lib');
				//console.log("start add img,img size:"+files.length);
				for(var i=0;i<files.length;i++){
					//console.log("add img:"+i);
					const file=files[i];
					var url = createURL(file); 
					const image = await getImage(url); 
					//console.log("img:",image.width,image.height);

					//console.log("pdf:");
					const imageType=getImageType(file.name);

					if(!imageType.isCommon){
						//console.log("使用新格式图像");
						const canvas = await getImageCanvas(image);
						url=canvas.toDataURL('image/jpeg', 0.93);				
					}
          const page = pdfDoc.addPage([image.width/k, image.height/k]);
          //console.log(page);
          const imageBytes = await fetch(url).then((res) => res.arrayBuffer());

          const pdfImage =imageType.type==='JPEG'? 
                        await pdfDoc.embedJpg(imageBytes)
                        :await pdfDoc.embedPng(imageBytes);

          await page.drawImage(pdfImage, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight()});
				}
				//pdf.save('download.pdf');
        const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
        downLoad(pdfDataUri,"download");
			};
			const input_file=document.getElementById("file1");
			input_file.addEventListener('change', function(event){
                if(this.files.length<1)return;
				const resolution = document.getElementById("resolution").value-0;
				//console.log("resolution:"+resolution,typeof(resolution));
				if(isNaN(resolution)|| resolution<72||resolution>1200){
					alert("分辨率必须在72~1200之间");
					return;
				}
				img2pdf(this.files);
			});
  </script>
</html>